import React from 'react';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import { Table, Button, message } from 'antd';
import _ from 'lodash';

import { getCol } from '../task/col';
import RecordModal from './recordModal';
import FileButton from '../../components/FileButton';
import { send } from './window';
import SideModal from '../../components/SideModal';
import SubmitList from '../submit/submitList';

/**
 * 单纯展示Record列表的组件
 */
class RecordList extends React.Component {

  constructor(p) {
    super(p);
    this.getRecOp = this.getRecOp.bind(this);
    this.action = this.action.bind(this);
    this.handleFileChange = this.handleFileChange.bind(this);
    this.state = {
      type: null,
      data: null,
      textLoading: false, // 当前文件是否解析中
      isShowSubmit: false, // 是否展示提交数据
      submitData: [], // 需要展示的提交数据
    };
    const recordKeys = [
      'id',
      'audio',
      'distributeNumber',
      'doneNumber',
      'lineNumber',
      'text',
      'last_dst_time',
      'image'].filter((key) => {
        return this.props.filterCol.indexOf(key) < 0;
      });
    this.columns = _.unionBy(getCol(recordKeys), this.getRecOp(), 'key');
  }

  componentDidMount() {
    const { dispatch, fatherId } = this.props;
    // 查询条目
    dispatch({
      type: 'record/queryRecord',
      payload: {
        id: fatherId,
      },
    });
  }

  // 获取表格中最后两个表头
  getRecOp() {
    const submitOp = {
      title: '提交记录',
      dataIndex: 'record',
      render: (text) => {
        // console.log('[RECORD_RECORD]', text);
        if (text && text.length) {
          return (<a onClick={this.showSubmit(text)}>详情</a>);
        }
        return '无提交';
      },
    };

    const ops = [
      {
        title: '操作',
        key: 'op',
        render: (text, record) => {
          return (
            <div>
              <a onClick={this.action('edit', record)} key="edit">编辑</a>
            |
            <a onClick={() => message.error('尚未开放')} key="delete">删除</a>
            </div>
          );
        },
      },
    ];

    if (this.props.hasRecord) {
      ops.unshift(submitOp);
    }
    return ops;
  }


  /**
   * 展示提交记录
   * @param {array} submits 提交记录
   */
  showSubmit(submits) {
    return () => {
      console.log('[USER_CLICL_SHOW_SUBMIT]', submits);
      this.setState({
        isShowSubmit: true,
        submitData: submits,
      });
    };
  }

  // 处理文件上传事件
  handleFileChange(e) {
    const { fatherId } = this.props;
    if (e.target && e.target.files && e.target.files.length !== 0) {
      const files = e.target.files;
      const fileReader = new FileReader(); // eslint-disable-line
      this.setState({
        textLoading: true,
      });
      const file = files[0];
      if (file) {
        fileReader.readAsText(files[0]);
      }
      fileReader.onloadend = (event) => {
        const filename = file.name;
        const content = event.target.result;
        send(filename, content, fatherId, () => {
          console.log('[RECORD_FILE_UPLOAD_SUCCESS]');
          this.componentDidMount();
        });
        this.setState({
          textLoading: false,
        });
      };
    }
  }


  action(type, data) {
    return () => {
      this.setState({
        type,
        data,
      });
      if (!type) {
        this.componentDidMount();
      }
    };
  }


  render() {
    const {
      records,
    } = this.props.record;
    const { loading, hideCreate } = this.props;
    const { type, data, isShowSubmit, submitData } = this.state;

    return (
      <div>
        {
          Boolean(type) && (
            <RecordModal
              type={type}
              visible={Boolean(type)}
              data={data}
              onFinish={this.action(null, null)}
            />
          )
        }
        <h3>条目列表:</h3>
        {
          !hideCreate && (
            [
              <h4>操作</h4>,
              <Button type="primary" onClick={this.action('create')}>新增条目</Button>,
              <span> &nbsp;&nbsp; </span>,
              <FileButton
                loading={this.state.textLoading}
                onChange={this.handleFileChange}
              >
                文件上传
              </FileButton>,
              <br />,
              <br />,
            ]
          )
        }
        <Table
          columns={this.columns}
          dataSource={records}
          loading={loading.effects['record/queryRecord']}
          rowKey="id"
        />
        <SideModal
          visible={isShowSubmit}
          onClose={() => {
            this.setState({
              isShowSubmit: false,
              submitData: [],
            });
          }}
        >
          <SubmitList submitData={submitData} mode="local" />
        </SideModal>
      </div>
    );
  }
}

RecordList.propTypes = {
  fatherId: PropTypes.string,
  loading: PropTypes.object,
  hideCreate: PropTypes.bool,
  hasRecord: PropTypes.bool, // 是否有Record这条属性
  filterCol: PropTypes.array, // 要删掉的属性
};

RecordList.defaultProps = {
  hideCreate: false,
  hasRecord: true,
  filterCol: [],
};

export default connect(state => state)(RecordList);
